<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\SystemLog;

class AuthController extends Controller
{
    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return $this->error('验证失败', 422, $validator->errors());
        }

        $username = $request->username;
        
        // 支持用户名或手机号登录
        $user = User::where('username', $username)
                   ->orWhere('phone', $username)
                   ->first();

        if (!$user) {
            return $this->error('用户不存在', 400);
        }

        if ($user->status !== 'active') {
            return $this->error('账号已被禁用或锁定', 400);
        }


        if (!Hash::check($request->password, $user->password)) {
            return $this->error('密码错误', 400);
        }

        // 更新登录信息
        $user->update([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip(),
            'last_login_device' => $request->userAgent()
        ]);

        // 创建API token
        $token = $user->createToken('auth-token')->plainTextToken;

        // 记录登录日志
        SystemLog::log(
            'login',
            'auth',
            '用户登录成功',
            $user->id,
            'User',
            $user->id,
            null,
            ['ip' => $request->ip(), 'device' => $request->userAgent()],
            'info',
            ['ip' => $request->ip(), 'device' => $request->userAgent()]
        );

        // 获取用户权限
        $permissions = $this->getUserPermissions($user);

        return $this->success([
            'user' => $user,
            'token' => $token,
            'permissions' => $permissions
        ], '登录成功');
    }

    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|min:2|max:20|unique:users',
            'phone' => 'required|string|unique:users|regex:/^1[3-9]\d{9}$/',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return $this->error('验证失败', 422, $validator->errors());
        }

        $user = User::create([
            'username' => $request->username,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'status' => 'active',
            'preferences' => [
                'language' => 'zh_CN',
                'theme' => 'light',
                'timezone' => 'Asia/Shanghai'
            ]
        ]);

        return $this->success($user, '注册成功', 201);
    }

    /**
     * 用户退出
     */
    public function logout(Request $request)
    {
        $user = $request->user();
        
        if ($user) {
            // 删除当前token
            $user->currentAccessToken()->delete();
            
            // 记录退出日志
            SystemLog::log(
                'logout',
                'auth',
                '用户退出登录',
                $user->id,
                'User',
                $user->id,
                null,
                ['ip' => $request->ip()],
                'info',
                ['ip' => $request->ip()]
            );
        }

        return $this->success(null, '退出成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        try {
            $user = $request->user();

            if (!$user) {
                return $this->error('未登录', 401);
            }

            // 只返回用户信息和权限，菜单数据通过单独的接口获取
            $permissions = $this->getUserPermissions($user);

            return $this->success([
                'user' => $user,
                'permissions' => $permissions
            ], '获取成功');
        } catch (\Exception $e) {
            return $this->error( '获取用户信息失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return $this->error('验证失败', 422, $validator->errors());
        }

        $user = $request->user();
        
        if (!Hash::check($request->current_password, $user->password)) {
            return $this->error('当前密码错误', 400);
        }

        $user->update([
            'password' => Hash::make($request->new_password),
            'password_changed_at' => now()
        ]);

        // 记录密码修改日志
        SystemLog::log(
            'change_password',
            'auth',
            '用户修改密码',
            $user->id,
            'User',
            $user->id,
            null,
            ['ip' => $request->ip()],
            'info',
            ['ip' => $request->ip()]
        );

        return $this->success(null, '密码修改成功');
    }

    /**
     * 更新个人信息
     */
    public function updateProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|min:2|max:20',
            'phone' => 'nullable|string|regex:/^1[3-9]\d{9}$/',
            'preferences' => 'nullable|array',
        ]);

        if ($validator->fails()) {
            return $this->error('验证失败', 422, $validator->errors());
        }

        $user = $request->user();
        
        // 检查用户名是否已被其他用户使用
        if ($request->username !== $user->username) {
            $existingUser = User::where('username', $request->username)
                               ->where('id', '!=', $user->id)
                               ->first();
            if ($existingUser) {
                return $this->error('用户名已被使用', 400);
            }
        }

        // 检查手机号是否已被其他用户使用
        if ($request->phone && $request->phone !== $user->phone) {
            $existingUser = User::where('phone', $request->phone)
                               ->where('id', '!=', $user->id)
                               ->first();
            if ($existingUser) {
                return $this->error('手机号已被使用', 400);
            }
        }

        $updateData = [
            'username' => $request->username,
            'phone' => $request->phone,
        ];

        // 更新偏好设置
        if ($request->has('preferences')) {
            $currentPreferences = $user->preferences ?? [];
            $newPreferences = array_merge($currentPreferences, $request->preferences);
            $updateData['preferences'] = $newPreferences;
        }

        $user->update($updateData);

        // 记录个人信息更新日志
        SystemLog::log(
            'update_profile',
            'auth',
            '用户更新个人信息',
            $user->id,
            'User',
            $user->id,
            null,
            ['updated_fields' => array_keys($updateData)],
            'info',
            ['updated_fields' => array_keys($updateData)]
        );

        return $this->success($user, '个人信息更新成功');
    }

    /**
     * 获取用户菜单树
     */
    private function getUserMenuTree($user)
    {
        try {
            // 使用Menu模型的静态方法获取用户菜单树
            $menus = \App\Models\Menu::getUserMenuTree($user);

            // 格式化菜单数据为前端需要的格式
            return $this->formatMenusForFrontend($menus);
        } catch (\Exception $e) {
            // 如果出错，返回空数组
            return [];
        }
    }

    /**
     * 格式化菜单数据为前端需要的格式
     */
    private function formatMenusForFrontend($menus)
    {
        return $menus->map(function ($menu) {
            $formatted = [
                'id' => $menu->id,
                'name' => $menu->name,
                'path' => $menu->path,
                'icon' => $menu->icon,
                'component' => $menu->component,
                'type' => $menu->type,
                'is_external' => $menu->is_external,
                'permissions' => $menu->permissions,
                'sort_order' => $menu->sort_order,
            ];

            // 如果有子菜单，递归处理
            if ($menu->children && $menu->children->count() > 0) {
                $formatted['children'] = $this->formatMenusForFrontend($menu->children);
            }

            return $formatted;
        });
    }

    /**
     * 获取用户权限
     */
    private function getUserPermissions($user)
    {
        try {
            $permissions = [];

            // 检查用户是否为超级管理员
            if ($user->hasRole('super_admin')) {
                return ['*'];
            }

            // 从用户的角色中收集权限
            foreach ($user->roles as $role) {
                if ($role->isActive() && $role->permissions) {
                    $permissions = array_merge($permissions, $role->permissions);
                }
            }

            return array_unique($permissions);
        } catch (\Exception $e) {
            // 如果出错，返回空数组
            return [];
        }
    }
}
